<?php
namespace Home\Controller;

use Utuo\MallForeground;
use Home\Logic\MallRedPacketLogic;

class MallTryController extends MallForeground {
	
	/**
	 * 初始化
	 */
	public function _init() {
		layout('Mall/layout');
		$this->setModelName('Mall');
		$this->setModelControllerName("Mall");
		if ( in_array(ACTION_NAME, array('index', 'show')) ) { // 支持跳转获得用户信息 
			$this->setSupportRedirect(isset($_REQUEST['debug'])?false:true);
		}
	}
	
	/**
	 * 免费列表
	 */
	public function indexAction() {
		$this->display("{$this->modelControllerName}/tryIndex");
	}
	
	/**
	 * 免费试用
	 */
	public function showAction() {
		$tryId = I('tryId', 0, "intval"); // 试用活动id
		$goodsId = I('goodsId', 0, "intval"); // 商品id
		$qid = $this->getQid() and $this->setQid($qid); // 渠道id
		$condition = array(
			'cid' => $this->cid,
			'status' => 1,
			'try' => 1,
		);
		$goodsId and $condition['id'] = $goodsId;
		$goods = M("MallGoods")->where($condition)->find();
		if ( $goods ) {
			$goods['attrs_cfg'] = unserialize($goods['attrs_cfg']);
			$goods['images'] = unserialize($goods['images']);
		} else {
			$this->error('当前没有试用商品');
		}
		
		/* 我的试用 */
		$myTry = $this->getMyTry($goods['id']);
		$tryId or $tryId = $myTry['id'];
		if ( $tryId and !$_GET['tryId'] ) {
			redirect($this->getCurrentUrl( array( 'tryId' => $tryId ) ));
		}
		
		/* 支持者 */
		if ( $tryId ) {
			$supported = 0;
			$supporters = M("MallTry a")->join("__MALL_TRY_SUPPORT__ b on b.tryId = a.id")
												->join("__WECHAT_USER__ c on c.id = b.supporter", "LEFT")
												->where('a.id=%d and a.cid=%d', $tryId, $this->sid)
												->field("a.times,c.id,c.nickname,c.face")
												->select();
			if ( M("MallTrySupport")->where("supporter=%d", $this->uid)->count() ) {
				$supported = 1;
			}
			
			$try = M("MallTry a")->where(array('a.id' => $tryId))->find();
			$try['successCount'] = M("MallTry a")->join("__MALL_TRY_SUPPORT__ b on a.id=b.tryId")
															 ->where('productId=%d', $goods['id'])->count();
		}
		
		$ready = 0; // 已有人数
		$total = 0; // 应有人数
		if ( !$supporters ) {
			$total = 10;
			$supporters = array_fill(0, $total, null);
		} else {
			$ready = count( $supporters );
			$times = $supporters[0]['times'];
			$total = $this->getTotalTimes($times);
			if ( $total - $ready > 0 ) {
				$supporters = array_merge($supporters, array_fill( 0, $total - $ready, null )) ;
			}
		}
		
		/* 是否本人试用的特殊处理 */
		if ( $try['uid'] != $this->uid ) {
			/* 试用发起人信息 */
			$wechatUser = M("WechatUser")->where("id=%d", $try['uid'])->find();
			$try['nickname'] = $nickname = $wechatUser['nickname'];
			$try['face'] = $face = $wechatUser['face'];
			$try['myself'] = 0;
			if ( !$this->user['subscribe'] ) {
				/* 试用发起人发起的试用链接 */
				S("referer_{$this->cid}_{$this->openId}", array(
					'link' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].($_SERVER['QUERY_STRING']?'?'.$_SERVER['QUERY_STRING']:''),
					'nickname' => $try['nickname'], // 试用发起人昵称
					'goodsName' => $goods['name'], // 试用商品
				));
				//echo "referer_{$this->cid}_{$this->openId}";
			}
		} else {
			/* 试用发起人信息 */
			$userId = $this->user['id'];
			$nickname = $this->user['nickname'];
			$try['myself'] = 1;
		}
		
		/* 分享 */
		$this->setShare(array(
			'img' => $goods['share_image'],
			'desc' => "我还差".(($total - $ready)?$total - $ready:0)."个好友支持，就可以领取试用产品，请点击链接支持我，同时请你一起来参与!",
			'title' => "我{$nickname}是\"{$goods['name']}\"的第{$try['id']}位试用参与者",
			'link' => U('MallTry/show', array( 'tryId' => $try['id'], 'sid' => $this->sid, 'mid' => $try['uid'], 'qid' => $qid ), false, true ),
		));
		
		/* 参与用户 */
		$tryList = M("MallTry a")->join("__WECHAT_USER__ b on a.uid = b.id")
											->where("a.productId=%d and a.times>=0 and a.cid=%d and b.face != ''", $goods['id'], $this->cid)
											->field("b.nickname, b.face")
											->order("a.id desc")
											->limit(50)
											->select();
		$this->assign("tryList", $tryList);
		
		$this->setPageTitle($goods['name']);
		$this->assign("try", $try); // 试用活动数据
		$this->assign("supporters", array('list' => $supporters, 'count' => $ready, 'diff' => $total - $ready, 'supported' => $supported ));
		$this->assign("shopGoods", $goods);
		$this->assign("qid", $qid);
		$this->display("{$this->modelControllerName}/tryShow");
	}
	
	/**
	 * 支持者点支持
	 */
	public function supportAction() {
		$tryId = I('tryId', 0, "intval") or $this->ajaxError("试用编号不存在");
		$mallTry = M("MallTry a")->join("__WECHAT_USER__ b on a.uid=b.id")
														->join("__MALL_GOODS__ c on a.productId=c.id")
														->field("a.*,b.openId,b.nickname,c.name as productName")->where('a.id=%d', $tryId)->find();
		if ( !$mallTry ) {
			$this->ajaxError("试用不存在");
		} else {
			if ( M("MallTrySupport")->where("supporter=%d", $this->uid)->count() ) {
				$this->ajaxError("谢谢您的参与,您已支持过了");
			} else {
				if ( false !== M("MallTrySupport")->add(array(
					'tryId' => $tryId,
					'supporter' => $this->uid,
					'createTime' => time(),
				))) {
					
					/* 创建红包 */
					$newRedPacket = MallRedPacketLogic::newRedPacket($this->cid, $this->uid, 10.00, 96.00, 'TRY_ACTIVE');
					MallRedPacketLogic::addRedPacket( $newRedPacket );
					
					/* 给支持者发送获得红包消息 */
					$data = array(
							"articles" => array(
									array(
											'title' => '获得10元红包通知',
											'description' => "{$this->user['nickname']}您好，恭喜您在参与\"{$mallTry['productName']}\"试用活动中支持了您的好友获得了10元红包，点击查看红包，可以在购买商品时冲抵现金。\n\n",
											'url' => U('MallRedPakcet/list', array('sid'=>$this->sid, 'type' => 1), false, true),
									)
							)
					);
					$this->sendServerMsg($this->openId, $data);
					
					/* 参与人数累加 */
					if ( false !== M("MallTry")->save(array(
						'id' => $tryId,
						'count' => array('exp', 'count+1'),
					)) ) {
						/* 给被支持者发送消息 */
						$number = $this->getTotalTimes($mallTry['times']) - ($mallTry['count'] + 1);
						$data = array(
							"articles" => array(
								array(
									'title' => '获得朋友支持通知',
									'description' => "Hi，{$mallTry['nickname']}，恭喜您又获得了一位朋友的支持。\n\n".
													"朋友昵称：{$this->user['nickname']}\n\n".
													"您现在的支持人数为".($mallTry['count'] + 1)."，还差{$number}位就可以试用我们的产品了\n\n".
													"如果您试用过我们的产品，不妨引导您的朋友一起来试用吧~",
									'url' => U('MallTry/show', array('sid'=>$this->sid, 'tryId'=>$tryId), false, true),
								)
							)
						);
						$this->sendServerMsg($mallTry['openId'], $data);						
						$this->ajaxSuccess('支持成功');
					}
				}
			}
		}
		$this->ajaxError('支持失败');
	}
	
	/**
	 * 领取试用商品
	 */
	public function drawGoodsAction() {
		$tryId = I('tryId', 0, "intval") or $this->error("试用编号不存在");
		$mallTry = M("MallTry")->where('id=%d', $tryId)->find();
		if ( !$mallTry ) {
			$this->ajaxError("试用不存在:$tryId");
		} else {
			$total = $this->getTotalTimes($mallTry['times']);
			$count = M("MallTrySupport")->where('tryId=%d', $tryId)->count();
			if ( $count >= $total ) {
				$data = array('tryId' => $tryId, "sid" => $this->sid);
				if ( $mallTry['status'] == 1 ) {
					$data['orderId'] = $mallTry['orderId'];
				}
				redirect(U("MallTryOrder/confirmOrder", $data));
			}
		}
		$this->error("领取失败");
	}
	
	/**
	 * 发送客服消息
	 * @param unknown $openId
	 * @param unknown $msg
	 */
	private function sendServerMsg( $openId, $data ) {
		$accessToken = $this->wechatAdvance->getBaseAccess();
		$this->wechatAdvance->sendServerMessage( $accessToken['access_token'], $openId, $data, 5 );
	}
	
	/**
	 * 开启试用
	 */
	private function getMyTry( $productId ) {
		if ( !$productId )
			return; 
		$try = M("MallTry")->where("productId=%d and uid=%d", $productId, $this->uid)->find();
		if ( $try ) { // 已发起试用过了
			return $try;
		} else {
			$try = array(
				'cid' => $this->cid,
				'uid' => $this->uid,
				'productId' => $productId,
				'times' => 0,
				'count' => 0,
				'status' => 0,
			);
			$try['id'] = M("MallTry")->add( $try );
			return $try;
		}
	}
	
	/**
	 * 获得第n次累计支持数
	 * @param int $times 累计已支持成功的次数 (从0开始)
	 */
	private function getTotalTimes( $times ) {
		$total = 0;
		for( $i = 1; $i <= $times*1 + 1; $i++ ) {
			$total += $i * 10;
		}
		return $total;
	}
	
}